package com.example.train_operate.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Map<String, Object> map = new HashMap();
        if (UserHolder.getUser() == null) {
            map.put("code", 202);
            map.put("data", null);
            map.put("message", "token无效！");
            String json = (new ObjectMapper()).writeValueAsString(map);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(json);
            return false;
        } else {
            return true;
        }
    }
}
